package com.antmall.prodouct.service.impl;

import com.antmall.common.entity.PageVO;

import com.antmall.prodouct.bo.ProdouctAddBO;
import com.antmall.prodouct.bo.ProdouctEditBO;
import com.antmall.prodouct.bo.ProdouctQueryBO;
import com.antmall.prodouct.entity.Product;
import com.antmall.prodouct.mapper.ProductMapper;
import com.antmall.prodouct.service.ProductService;
import com.antmall.prodouct.vo.ProdouctQueryVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;

import java.util.List;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {


    public void add(ProdouctAddBO prodouctAddBO) {
        Product product = new Product();
        BeanUtils.copyProperties(prodouctAddBO, product);

        save(product);
    }


    public void edit(ProdouctEditBO prodouctEditBO) {
        Product product = new Product();
        BeanUtils.copyProperties(prodouctEditBO, product);

        updateById(product);
    }


    public PageVO<ProdouctQueryVO> page(ProdouctQueryBO prodouctQueryBO) {
        Page<Product> pageRquest = new Page<>(prodouctQueryBO.getCurrentPage(), prodouctQueryBO.getPageSize());
        Page<Product> page = lambdaQuery()
                .eq(StringUtils.hasText(prodouctQueryBO.getName()),
                        Product::getName, prodouctQueryBO.getName())
                .like(StringUtils.hasText(prodouctQueryBO.getDescription()),
                        Product::getDescription, prodouctQueryBO.getDescription())
                .orderByAsc(Product::getCreateTime)
                .page(pageRquest);

        PageVO<ProdouctQueryVO> pageVO = new PageVO<>();
        pageVO.setCurrentPage(page.getCurrent());
        pageVO.setPageSize(page.getSize());
        pageVO.setTotalSize(page.getTotal());

        List<ProdouctQueryVO> prodouctQueryVOList = new ArrayList<>();
        List<Product> productList = page.getRecords();
        for (Product product : productList) {
            ProdouctQueryVO prodouctQueryVO = new ProdouctQueryVO();
            BeanUtils.copyProperties(product, prodouctQueryVO);
            prodouctQueryVOList.add(prodouctQueryVO);
        }

        pageVO.setDataList(prodouctQueryVOList);


        return pageVO;
    }


    public void delete(List<Long> idList) {
        removeByIds(idList);
    }


}
